<<template>
  <div class="product-list">
    <!-- 添加按钮、模糊搜索、查询按钮 -->
    <!-- {{ searchForm }}
    ----
    {{ tableData }} -->
    <div class="search">
      <el-button class="btn" type="primary" @click="toAdd">添加</el-button>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="searchForm.name"
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="正常" value="正常"></el-option>
            <el-option label="下架" value="下架"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.productCategoryId"
            placeholder="请选择栏目"
            clearable
          >
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="toSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div>
      <el-table :data="tableData" style="width: 100%" :v-loading="loading">
        <el-table-column type="index" label="序号" align="center">
        </el-table-column>
        <el-table-column prop="id" label="产品编号" align="center">
        </el-table-column>
        <el-table-column prop="name" label="名称" align="center">
        </el-table-column>
        <el-table-column label="图片" align="center">
          <template slot-scope="scope">
            <!-- {{ scope.row.photo }} -->
            <!-- <img :src="scope.row.photo" /> -->
            <el-image
              style="width: 50px"
              :src="scope.row.photo"
              :preview-src-list="[scope.row.photo]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" align="center">
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '正常' ? '' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="category.name"
          label="所属栏目"
        ></el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button @click="toEdit(scope.row)" type="text">
              编辑
            </el-button>
            <el-button
              class="color_red"
              @click="toOnline(scope.row.id)"
              type="text"
              v-if="scope.row.status === '下架'"
            >
              上架
            </el-button>
            <el-button
              class="color_red"
              @click="toOffline(scope.row.id)"
              type="text"
              v-else
            >
              下架
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 模态框 -->
    <!-- :before-close="toClose" -->
    <el-dialog :title="title" :visible.sync="visible" @close="toClose">
      <!-- {{ form }} -->
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item
          prop="name"
          label="产品名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          prop="productCategoryId"
          label="所属栏目"
          :label-width="formLabelWidth"
          clearable
        >
          <el-select
            v-model="form.productCategoryId"
            placeholder="请选择所属栏目"
          >
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="price" label="价格" :label-width="formLabelWidth">
          <el-input v-model.number="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="photo" label="封面" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="产品描述" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="form.description"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageQuery } from "@/api/proCategory";
// 重命名
import {
  pageQuery as pageQueryProdt,
  saveOrUpdate,
  online,
  offline,
} from "@/api/product";
import { showFileURL, uploadFileURL } from "@/utils/config";

export default {
  data() {
    return {
      showFileURL,
      uploadFileURL,
      // 产品栏目的数据，页面一上来，就发请求，请求所有的产品栏目数据，设置到categoryData。
      categoryData: [],
      // 模糊搜索表单的数据
      searchForm: {
        name: "",
        status: "",
        productCategoryId: "",
      },
      // 表格展示的数据
      tableData: [],
      params: {
        page: 1,
        pageSize: 10,
      },
      // 总条数
      total: 0,
      // 表格加载中
      loading: false,
      // 模态框显示与隐藏
      visible: false,
      // 表单数据
      form: {},
      // 表单控件标题的宽度
      formLabelWidth: "80px",
      // 模态框的标题
      title: "",
      // 上传图片的路径
      imageUrl: "",
      // 校验规则
      rules: {
        name: [
          {
            required: true,
            message: "请输入产品名称",
            trigger: "blur",
          },
        ],
        productCategoryId: [
          {
            required: true,
            message: "请选择所属栏目",
            trigger: "change",
          },
        ],
        price: [
          {
            required: true,
            message: "请输入产品价格",
            trigger: "blur",
          },
          {
            type: "number",
            message: "价格必须为数字值",
            trigger: "blur",
          },
        ],
        // photo: [
        //   {
        //     required: true,
        //     message: "请上传封面图片",
        //   },
        // ],
      },
    };
  },
  watch: {
    // 深度监听分页参数
    params: {
      handler() {
        this.queryTabaData();
      },
      deep: true,
    },
  },
  computed: {},
  methods: {
    //   获取产品分类数据
    async queryCategoryData() {
      let res = await pageQuery({ page: 1, pageSize: 10 });
      this.categoryData = res.data.list;
    },
    // 分页模糊获取产品数据
    async queryTabaData() {
      this.loading = true;
      let temp = { ...this.params, ...this.searchForm };
      for (let key in temp) {
        // key是一个变量，代表的属性名
        if (!temp[key]) delete temp[key];
      }
      let res = await pageQueryProdt(temp);
      // 加载完毕
      this.loading = false;
      this.tableData = res.data.list;
      this.total = res.data.total;
    },
    // 查询按钮点击事件处理程序
    async toSearch() {
      this.queryTabaData();
    },
    // 每页显示的条数发生变化时的事件处理程序
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      // this.params.pageSize = val;
      this.params = {
        page: 1,
        pageSize: val,
      };
      // this.queryTabaData();
    },
    // 当前页码发生变化时的事件处理程序
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.params.page = val;
      // this.queryTabaData();
    },
    toAdd() {
      this.queryCategoryData();
      // 清空表单数据
      this.form = {};
      this.imageUrl = "";
      this.title = "添加产品信息";
      this.visible = true;
    },
    // 图片上传成功的回调函数
    handleAvatarSuccess(res, file) {
      // console.log(res, "==图片上传成功之后的res");
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(this.imageUrl);
      this.form.photo = showFileURL + res.data.id;
    },
    // 图片上传之前的回调函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    toSave() {
      // ref会保存在refs里
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          // 校验通过
          let res = await saveOrUpdate(this.form);
          // console.log(res);
          // 提示用户保存成功，刷新表格数据，关闭模态框
          this.$notify({
            title: "成功",
            message: res.message,
            type: "success",
          });
          this.queryTabaData();
          // this.toClose();
          this.visible = false;
        } else {
          return false;
        }
      });
    },
    // 关闭模态框
    toClose() {
      // 重置表单验证
      this.$refs.ruleForm.resetFields();
      // 关闭模态框
      // 超市调用
      // setTimeout(() => {
      //   this.visible = false;
      // }, 200);
    },
    // 编辑按钮的事件处理程序
    toEdit(row) {
      this.queryCategoryData();
      // 设置表单数据
      this.form = { ...row };
      this.imageUrl = this.form.photo;
      this.title = "编辑产品信息";
      this.visible = true;
    },
    // 上架产品
    async toOnline(id) {
      let res = await online({ id });
      this.$notify.success({
        title: "成功",
        message: res.message,
      });
      this.queryTabaData();
    },
    // 下架产品
    async toOffline(id) {
      let res = await offline({ id });
      this.$notify.success({
        title: "成功",
        message: res.message,
      });
      this.queryTabaData();
    },
  },
  created() {
    this.queryCategoryData();
    this.queryTabaData();
  },
  mounted() {},
};
</script>
<style lang="scss" scoped>
.search {
  .btn {
    margin-right: 10px;
  }
  form {
    display: inline;
  }
}
.page {
  float: right;
  margin-top: 20px;
}
.color_red {
  color: #e65d6e;
}
</style>